package com.elm.dao;

import com.elm.entity.Food;
import com.elm.entity.OrderDetailet;
import com.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderDetailetDao {
    private final FoodDao foodDao;
    public OrderDetailetDao() {
        foodDao = new FoodDao();
    }


    public List<OrderDetailet> getListByOrderId(int orderId) throws SQLException {
        String sql = "select * from orderdetailet where orderId=?";
        List<OrderDetailet> list = new ArrayList<>();
        try(Connection connection = DBUtil.getConnection();
            PreparedStatement ps = connection.prepareStatement(sql)){
            ps.setInt(1, orderId);
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                OrderDetailet orderDetailet = new OrderDetailet();
                orderDetailet.setOrderId(orderId);
                orderDetailet.setOdId(rs.getInt("odId"));
                orderDetailet.setFoodId(rs.getInt("foodId"));
                orderDetailet.setQuantity(rs.getInt("quantity"));
                Food food = foodDao.getFoodById(rs.getInt("foodId"));
                orderDetailet.setFood(food);
                list.add(orderDetailet);
            }
        }catch(SQLException e){
            e.printStackTrace();
        }
        return list;
    }


    public void saveOrderDetailet(List<OrderDetailet> orderDetailetList) throws SQLException {
        if (orderDetailetList == null || orderDetailetList.isEmpty()) {
            return; // 空列表直接返回
        }

        String sql = "INSERT INTO orderDetailet (orderId, foodId, quantity) VALUES (?, ?, ?)";

        try (Connection connection = DBUtil.getConnection();
             PreparedStatement ps = connection.prepareStatement(sql)) {

            // 关闭自动提交，开启事务
            connection.setAutoCommit(false);

            for (OrderDetailet detail : orderDetailetList) {
                ps.setInt(1, detail.getOrderId());
                ps.setInt(2, detail.getFoodId());
                ps.setInt(3, detail.getQuantity());
                ps.addBatch(); // 添加到批处理
            }

            // 执行批处理
            int[] result = ps.executeBatch();

            // 验证所有记录是否插入成功
            for (int i : result) {
                if (i == PreparedStatement.EXECUTE_FAILED) {
                    connection.rollback(); // 任何失败则回滚
                    throw new SQLException("批量插入失败，已回滚事务");
                }
            }

            connection.commit(); // 全部成功则提交

        } catch (SQLException e) {
            // 异常处理（日志记录等）
            throw e;
        } finally {
            // 注意：try-with-resources会自动关闭连接
        }
    }
}
